﻿using System.Collections.Generic;
using System.Text;
using PacketRush.Core;

namespace PacketRush.Services.Messaging
{
    public class ClientMessagingService : INetService
    {
        private PacketWriter _PacketWriter = new PacketWriter();
        private Queue<TextMessage> _Messages = new Queue<TextMessage>(16);
        public Queue<TextMessage> Messages
        {
            get
            {
                return _Messages;
            }
        }

        private Queue<Packet> _OutgoingPackets = new Queue<Packet>(16);
        public void DeliverPacket(Packet packet)
        {
            PacketReader reader = new PacketReader(packet);
            string message = reader.ReadString(Encoding.UTF8);
            _Messages.Enqueue(new TextMessage() { ConnectionId = packet.SenderId, Message = message  });
        }

        public Packet CollectPacket()
        {
            if (_OutgoingPackets.Count > 0)
            {
                return _OutgoingPackets.Dequeue();
            }
            return null;
        }

        public void SendMessage(string message)
        {
            _PacketWriter.Reset();
            _PacketWriter.Write(message, Encoding.UTF8);
            _OutgoingPackets.Enqueue(_PacketWriter.ToPacket(PacketFlags.Reliable));
        }
    }

    public class TextMessage
    {
        public int ConnectionId { get; set; }
        public string Message { get; set; }
    }
}
